<?php

namespace App\Service\GuildManage;

use App\Constants\ErrorCode;
use App\Constants\GuildCode;
use App\Exception\ApiException;
use App\Model\GuildManage\GuildAccount;
use App\Service\BaseService;
use App\Service\ServiceTrait\GetUserInfoTrait;
use App\Service\ServiceTrait\GuildTrait;
use Hyperf\Di\Annotation\Inject;

class AddBaseService extends BaseService
{
    use GuildTrait;

    /**
     * 执行动作的人
     * @var mixed
     */
    private $actionUserId;

    /**
     * @Inject
     * @var GuildAccount
     */
    protected $guildAccountModel;

    /**
     * 主控制器
     * @return mixed
     */
    public function handle()
    {
        $this->actionUserId = $this->getUserId();

        $type = $this->request->input('type', 0);

        $factory = new WithdrawFactory();
        switch ($type) {
            case 1:
                $service = $factory->addCard();

                $service->cardAccount = $this->request->input('bank_card', '');
                break;
            case 2:
                $service = $factory->addAlipay();

                $service->alipay = $this->request->input('alipay', '');
                break;
            default:
                throw new ApiException('操作异常!', ErrorCode::PARAMETER_ERROR);
        }

        if (!$this->checkGuildStatus($this->actionUserId)) {
            throw new ApiException('亲,暂时没有此操作权限哦!', ErrorCode::DEFAULT_ERROR);
        }

        $this->checkAccountCount();

        //设置默认值
        $defaultValue = 0;
        $default = $this->guildAccountModel->getDefaultAccountByUserId($this->actionUserId);
        if (empty($default)) {
            $defaultValue = 1;
        }

        $guildAccountModel = new GuildAccount();

        $guildAccountModel->account = $service->addAccount();
        $guildAccountModel->user_id = $this->actionUserId;
        $guildAccountModel->type = $type;
        $guildAccountModel->real_name = $this->request->input('name');
        $guildAccountModel->id_card = $this->request->input('id_card');
        $guildAccountModel->default = $defaultValue;
        $guildAccountModel->status = GuildAccount::STATUS_AUDIT;

        if (!$guildAccountModel->save()) {
            throw new ApiException('添加账户失败', ErrorCode::DEFAULT_ERROR);
        }

        return ['msg' => '添加成功'];
    }

    /**
     * 检查是否有数据超过
     * @return void
     */
    private function checkAccountCount()
    {
        if ($this->guildAccountModel->getCountByUserId($this->actionUserId) > GuildCode::ACCOUNT_MAX_NUM) {
            throw new ApiException('目前已经绑定了' . GuildCode::ACCOUNT_MAX_NUM . '个账户了哦');
        }
    }
}